package org.iabako.client.ui.form.business.report;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.ui.layout.field.CheckboxBoolean;
import org.iabako.client.ui.layout.field.InputTextDate;
import org.iabako.client.ui.layout.field.SelectList;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.shared.dto.ReportByEnum;
import org.iabako.shared.entity.business.CustomField;
import org.iabako.shared.iservice.business.CustomFieldServiceAsync;
import org.iabako.shared.iservice.report.IncomeReportGeneratorServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jose on 22/01/15.
 */
public class IncomeReportForm extends AbstractReportForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, IncomeReportForm> {
    }

    private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

    protected final IncomeReportGeneratorServiceAsync incomeReportGeneratorServiceAsync = IncomeReportGeneratorServiceAsync.Util.getInstance();
    private final CustomFieldServiceAsync customFieldServiceAsync = CustomFieldServiceAsync.Util.getInstance();

    @UiField
    SelectList groupBy;
    @UiField
    InputTextDate salesAfter;
    @UiField
    InputTextDate salesBefore;
    @UiField
    CheckboxBoolean incomeByClient;
    @UiField
    CheckboxBoolean incomeBySale;
    @UiField
    CheckboxBoolean incomeByInvoice;

    private ReportByEnum reportByEnum = null;

    @UiConstructor
    public IncomeReportForm() {
        initWidget(binder.createAndBindUi(this));

        setHandlers();

        setDefaultValues();
    }

    private void setDefaultValues() {
        incomeByClient.setValue(true);
        reportByEnum = ReportByEnum.byClient;
        Date date = GenericTools.getDateWithoutTime();
        date.setDate(1);
        salesAfter.setValue(date);
        salesBefore.setValue(GenericTools.getDateWithoutTime());

        customFieldServiceAsync.getCustomFields(new IabakoAsyncCallback<List<CustomField>>() {

            public void onSuccess(List<CustomField> result) {
                if (result.isEmpty()) {
                    groupBy.setVisible(false);
                } else {
                    Map<Long, String> customFields = new HashMap<Long, String>();
                    for (CustomField customField : result) {
                        customFields.put(customField.getId(), customField.getTitle());
                    }
                    groupBy.setValues(customFields);
                }
                super.onSuccess(result);
            }
        });
    }

    private void setHandlers() {

        incomeByClient.getCheckbox().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (incomeByClient.getValue()) {
                    incomeBySale.setValue(false);
                    incomeByInvoice.setValue(false);
                } else {
                    incomeByClient.setValue(true);
                }
                reportByEnum = ReportByEnum.byClient;
            }
        });
        incomeBySale.getCheckbox().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (incomeBySale.getValue()) {
                    incomeByClient.setValue(false);
                    incomeByInvoice.setValue(false);
                } else {
                    incomeBySale.setValue(true);
                }
                reportByEnum = ReportByEnum.bySale;
            }
        });
        incomeByInvoice.getCheckbox().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                if (incomeByInvoice.getValue()) {
                    incomeByClient.setValue(false);
                    incomeBySale.setValue(false);
                    incomeByInvoice.setValue(true);
                } else {
                    incomeByInvoice.setValue(true);
                }
                reportByEnum = ReportByEnum.byInvoice;
            }
        });

        generateReportAction.getButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {

                if (validateMandatoryFields()) {

                    reportGenerationInputDTO.setPeriod1DateAfter(GenericTools.formatDateToString(salesAfter.getDateValue()));
                    reportGenerationInputDTO.setPeriod1DateBefore(GenericTools.formatDateToString(salesBefore.getDateValue()));
                    reportGenerationInputDTO.setGroupBy((CustomField) groupBy.getValue());
                    reportGenerationInputDTO.setReportByEnum(reportByEnum);

                    incomeReportGeneratorServiceAsync.generateIncomeReport(reportGenerationInputDTO, new IabakoAsyncCallback<String>() {

                        public void onSuccess(String result) {
                            generateForm.setMethod("GET");
                            reportGeneratorFileToken.setValue(result);
                            generateForm.submit();
                            super.onSuccess(result);
                        }
                    });
                }

            }
        });
    }

    private boolean validateMandatoryFields() {
        if (!incomeByClient.getValue() && !incomeBySale.getValue()
                && !incomeByInvoice.getValue()) {

            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "report_income_sales_by_mandatory");
            return false;

        } else if (GenericTools.isEmpty(salesAfter.getDateValue(), salesBefore.getDateValue())) {

            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "report_income_dates_mandatory");
            return false;

        } else if (salesAfter.getDateValue().compareTo(salesBefore.getDateValue()) > 0) {

            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "report_income_dates_error");
            return false;
        }

        return true;
    }
}
